package org.xxpay.pay.channel.yipay;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xxpay.core.common.domain.api.AbstractRes;
import org.xxpay.core.common.domain.api.ApiBuilder;
import org.xxpay.core.common.domain.api.PayRes;
import org.xxpay.core.common.domain.api.msg.QueryRetMsg;
import org.xxpay.core.common.util.AmountUtil;
import org.xxpay.core.common.util.JsonUtil;
import org.xxpay.core.common.util.MyLog;
import org.xxpay.core.common.vo.DBApplicationConfig;
import org.xxpay.core.entity.PayOrder;
import org.xxpay.pay.channel.BasePayment;
import org.xxpay.pay.mq.BaseNotify4MchPay;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class YipayPaymentService extends BasePayment {

    @Autowired
    public BaseNotify4MchPay baseNotify4MchPay;

    private static final MyLog _log = MyLog.getLog(YipayPaymentService.class);

    @Override
    public String getChannelName() {
        return YipayConfig.CHANNEL_NAME;
    }

    /**
     * 支付
     * @param payOrder
     * @return
     */
    @Override
    public AbstractRes pay(PayOrder payOrder) {
        String channelId = payOrder.getChannelId();
        AbstractRes retObj;
        switch (channelId) {
            case YipayConfig.CHANNEL_NAME_ALIPAY_QR :
                retObj = doPay(payOrder, YipayConfig.CHANNEL_PAY_TYPE);
                break;
            case YipayConfig.CHANNEL_NAME_ALIPAY_H5 :
                retObj = doPay(payOrder, YipayConfig.CHANNEL_PAY_TYPE_123);
                break;
            default:
                retObj = ApiBuilder.bizError("不支持的渠道[channelId="+channelId+"]");
                break;
        }
        return retObj;
    }

    /**
     *
     * @param payOrder
     * @return
     */
    public AbstractRes doPay(PayOrder payOrder, String type) {
        YipayConfig lfpayConfig = new YipayConfig(getPayParam(payOrder));
        PayRes retObj = ApiBuilder.buildSuccess(PayRes.class);
        DBApplicationConfig dbConfig = getDBApplicationConfig();
        Map<String, Object> post= new HashMap<>();
        post.put("paytype", type); // 支付类型
        post.put("out_trade_no", payOrder.getPayOrderId());// 订单号
        post.put("notify_url", super.getNotifyUrl(getChannelName(), dbConfig));// 回调地址
        post.put("return_url", super.getReturnUrl(getChannelName(), dbConfig));// 跳转地址
        post.put("goodsname", payOrder.getSubject());// 商品名称
        post.put("total_fee", AmountUtil.convertCent2DollarShort(payOrder.getAmount()+""));// 定单金额，不要带小数，必须是整数
        post.put("requestip", getClientIp(payOrder));// 玩家的IP。

        try {
            //生成签名
            Map<String, Object> post1=new HashMap<String, Object>();
            UUID uuid = UUID.randomUUID();
            post1.put("mchid", lfpayConfig.getMchId()); // 商户ID
            post1.put("timestamp", System.currentTimeMillis()/1000); // 时间戳
            post1.put("nonce", uuid); // 商户ID

            Map<String, Object> post2 = new HashMap<String, Object>();
            post2.putAll(post);
            post2.putAll(post1);
            post1.put("sign", YipayUtils.getSign(post2,lfpayConfig.getKey()));//商户密钥,请自行修改
            post1.put("data",post); //合并真正提交的参数JSON
            JSONObject json = new JSONObject(post1);

            _log.info("{}请求数据:{}", getChannelName(), post1);
            String result = YipayUtils.sendPostJson(lfpayConfig.getReqUrl() + "/api/pay/gopay", json.toJSONString());
            _log.info("{}返回数据:{}", getChannelName(), result);
            JSONObject jsonObject = JsonUtil.getJSONObjectFromJson(result);
            String code = jsonObject.getString("error");
            if("0".equals(code)) {
                JSONObject data = jsonObject.getJSONObject("data");
                String payUrl = data.getString("payurl");     // 支付URL
                int updateCount = commonService.payOrderService.updateStatus4Ing(payOrder.getPayOrderId(), null);
                _log.info("[{}]更新订单状态为支付中:payOrderId={},payUrl={},payType={},result={}", getChannelName(), payOrder.getPayOrderId(), payUrl, type, updateCount);
                retObj.setJumpInfo("<script>location.href='" + payUrl + "';</script>", payUrl);
                return retObj;
            }else {
                String msg = jsonObject.getString("msg");
                return ApiBuilder.bizError("调起通道失败[通道提示：" + msg +"]");
            }
        } catch (Exception e) {
            _log.error(e, "");
            return ApiBuilder.bizError("调起通道异常");
        }
    }

    /**
     * 查询订单
     * @param payOrder
     * @return
     */
    @Override
    public QueryRetMsg query(PayOrder payOrder) {
        String logPrefix = "【" + getChannelName() + "支付订单查询】";
        String payOrderId = payOrder.getPayOrderId();
        _log.info("{}开始查询,payOrderId={}", logPrefix, payOrderId);
        return QueryRetMsg.waiting();
    }

}
